"use client"

import { useState, useEffect } from "react"
import {
  Form,
  Input,
  Button,
  Space,
  Table,
  Tag,
  Popconfirm,
  message,
  Typography,
  Card,
  Modal,
  Tabs,
  ColorPicker,
  Select,
} from "antd"
import {
  TeamOutlined,
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  GlobalOutlined,
  ApiOutlined,
  DatabaseOutlined,
  CloudOutlined,
  AppstoreOutlined,
  CodeOutlined,
} from "@ant-design/icons"
import { useHosts } from "../contexts/HostsContext"
import type { Department, HostTypeDefinition } from "../types"

const { TextArea } = Input
const { Title, Text } = Typography
const { TabPane } = Tabs

const SettingsPage = () => {
  const {
    departments,
    projects,
    hostTypes,
    addDepartment,
    updateDepartment,
    deleteDepartment,
    addHostType,
    updateHostType,
    deleteHostType,
  } = useHosts()

  const [departmentForm] = Form.useForm()
  const [hostTypeForm] = Form.useForm()
  const [editingDepartmentId, setEditingDepartmentId] = useState<string | null>(null)
  const [editingHostTypeId, setEditingHostTypeId] = useState<string | null>(null)
  const [isDeleteModalVisible, setIsDeleteModalVisible] = useState(false)
  const [departmentToDelete, setDepartmentToDelete] = useState<Department | null>(null)
  const [activeTab, setActiveTab] = useState("departments")

  useEffect(() => {
    if (editingDepartmentId) {
      const department = departments.find((d) => d.id === editingDepartmentId)
      if (department) {
        departmentForm.setFieldsValue({
          name: department.name,
          code: department.code,
          description: department.description,
          color: department.color,
        })
      }
    }
  }, [editingDepartmentId, departments, departmentForm])

  useEffect(() => {
    if (editingHostTypeId) {
      const hostType = hostTypes.find((h) => h.id === editingHostTypeId)
      if (hostType) {
        hostTypeForm.setFieldsValue({
          name: hostType.name,
          code: hostType.code,
          description: hostType.description,
          color: hostType.color,
          icon: hostType.icon,
        })
      }
    }
  }, [editingHostTypeId, hostTypes, hostTypeForm])

  const handleAddDepartment = (values: any) => {
    // Ensure we have a color value
    const colorValue = values.color || "#3b82f6"

    if (editingDepartmentId) {
      // Update existing department
      updateDepartment(editingDepartmentId, {
        name: values.name,
        code: values.code,
        description: values.description,
        color: colorValue,
      })
      message.success("部门更新成功")
    } else {
      // Add new department
      addDepartment({
        name: values.name,
        code: values.code,
        description: values.description,
        color: colorValue,
      })
      message.success("部门添加成功")
    }
    departmentForm.resetFields()
    setEditingDepartmentId(null)
  }

  const handleAddHostType = (values: any) => {
    // Ensure we have a color value
    const colorValue = values.color || "#3b82f6"

    if (editingHostTypeId) {
      // Update existing host type
      updateHostType(editingHostTypeId, {
        name: values.name,
        code: values.code,
        description: values.description,
        color: colorValue,
        icon: values.icon,
      })
      message.success("主机类型更新成功")
    } else {
      // Add new host type
      addHostType({
        name: values.name,
        code: values.code,
        description: values.description,
        color: colorValue,
        icon: values.icon || "AppstoreOutlined",
      })
      message.success("主机类型添加成功")
    }
    hostTypeForm.resetFields()
    setEditingHostTypeId(null)
  }

  const handleDeleteDepartment = (department: Department) => {
    // Check if there are projects in this department
    const departmentProjects = projects.filter((p) => p.departmentId === department.id)
    if (departmentProjects.length > 0) {
      setDepartmentToDelete(department)
      setIsDeleteModalVisible(true)
    } else {
      deleteDepartment(department.id)
      message.success("部门删除成功")
    }
  }

  const handleDeleteHostType = (hostType: HostTypeDefinition) => {
    deleteHostType(hostType.id)
  }

  const getIconComponent = (iconName: string) => {
    switch (iconName) {
      case "GlobalOutlined":
        return <GlobalOutlined />
      case "ApiOutlined":
        return <ApiOutlined />
      case "DatabaseOutlined":
        return <DatabaseOutlined />
      case "CloudOutlined":
        return <CloudOutlined />
      case "CodeOutlined":
        return <CodeOutlined />
      default:
        return <AppstoreOutlined />
    }
  }

  const departmentColumns = [
    {
      title: "名称",
      dataIndex: "name",
      key: "name",
      render: (text: string) => <Text strong>{text}</Text>,
    },
    {
      title: "代码",
      dataIndex: "code",
      key: "code",
      render: (code: string, record: Department) => (
        <Tag
          className="status-badge"
          style={{
            backgroundColor: record.color ? `${record.color}20` : "#e0f2fe",
            color: record.color || "#0284c7",
          }}
        >
          {code}
        </Tag>
      ),
    },
    {
      title: "颜色",
      dataIndex: "color",
      key: "color",
      render: (color: string) => (
        <div
          style={{
            width: "24px",
            height: "24px",
            borderRadius: "4px",
            backgroundColor: color || "#3b82f6",
          }}
        />
      ),
    },
    {
      title: "描述",
      dataIndex: "description",
      key: "description",
      ellipsis: true,
    },
    {
      title: "项目数",
      key: "projectCount",
      render: (text: string, record: Department) => {
        const count = projects.filter((p) => p.departmentId === record.id).length
        return <Tag className="status-badge status-test">{count}</Tag>
      },
    },
    {
      title: "操作",
      key: "action",
      render: (text: string, record: Department) => (
        <Space size="small">
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => {
              setEditingDepartmentId(record.id)
              departmentForm.setFieldsValue({
                name: record.name,
                code: record.code,
                description: record.description,
                color: record.color,
              })
            }}
          />
          <Popconfirm
            title="确定要删除此部门吗？"
            onConfirm={() => handleDeleteDepartment(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="text" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ]

  const hostTypeColumns = [
    {
      title: "名称",
      dataIndex: "name",
      key: "name",
      render: (text: string, record: HostTypeDefinition) => (
        <Space>
          <div
            style={{
              width: "24px",
              height: "24px",
              borderRadius: "4px",
              backgroundColor: record.color,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              color: "white",
            }}
          >
            {getIconComponent(record.icon)}
          </div>
          <Text strong>{text}</Text>
        </Space>
      ),
    },
    {
      title: "代码",
      dataIndex: "code",
      key: "code",
      render: (code: string, record: HostTypeDefinition) => (
        <Tag
          className="status-badge"
          style={{
            backgroundColor: `${record.color}20`,
            color: record.color,
          }}
        >
          {code}
        </Tag>
      ),
    },
    {
      title: "描述",
      dataIndex: "description",
      key: "description",
      ellipsis: true,
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
      key: "createdAt",
      render: (date: string) => new Date(date).toLocaleDateString(),
    },
    {
      title: "操作",
      key: "action",
      render: (text: string, record: HostTypeDefinition) => (
        <Space size="small">
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => {
              setEditingHostTypeId(record.id)
              hostTypeForm.setFieldsValue({
                name: record.name,
                code: record.code,
                description: record.description,
                color: record.color,
                icon: record.icon,
              })
            }}
          />
          <Popconfirm
            title="确定要删除此主机类型吗？"
            onConfirm={() => handleDeleteHostType(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="text" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ]

  return (
    <div className="fade-in">
      <div className="page-header mb-6">
        <Title level={4} className="page-title">
          系统设置
        </Title>
        <Text type="secondary">管理系统基础配置，包括部门和主机类型</Text>
      </div>

      <Tabs activeKey={activeTab} onChange={setActiveTab} className="settings-tabs">
        <TabPane
          tab={
            <span>
              <TeamOutlined /> 部门管理
            </span>
          }
          key="departments"
        >
          <div style={{ display: "flex", gap: "24px" }}>
            <Card className="enhanced-card" style={{ flex: 1 }}>
              <Title level={5} style={{ marginBottom: "16px" }}>
                部门列表
              </Title>
              <Table
                columns={departmentColumns}
                dataSource={departments}
                rowKey="id"
                pagination={{ pageSize: 10 }}
                className="enhanced-table"
              />
            </Card>

            <Card className="enhanced-card" style={{ width: "350px" }}>
              <Title level={5} style={{ marginBottom: "16px" }}>
                {editingDepartmentId ? "编辑部门" : "添加部门"}
              </Title>
              <Form form={departmentForm} layout="vertical" onFinish={handleAddDepartment}>
                <Form.Item name="name" label="部门名称" rules={[{ required: true, message: "请输入部门名称" }]}>
                  <Input placeholder="如：IT部门" />
                </Form.Item>
                <Form.Item name="code" label="部门代码" rules={[{ required: true, message: "请输入部门代码" }]}>
                  <Input placeholder="如：IT" />
                </Form.Item>
                <Form.Item name="color" label="部门颜色">
                  <ColorPicker
                    showText
                    format="hex"
                    value={departmentForm.getFieldValue("color") || "#3b82f6"}
                    onChange={(color, hex) => departmentForm.setFieldValue("color", hex)}
                  />
                </Form.Item>
                <Form.Item name="description" label="部门描述">
                  <TextArea rows={4} placeholder="请输入部门描述" />
                </Form.Item>
                <Form.Item>
                  <Space>
                    <Button
                      type="primary"
                      htmlType="submit"
                      icon={editingDepartmentId ? <EditOutlined /> : <PlusOutlined />}
                    >
                      {editingDepartmentId ? "更新" : "添加"}
                    </Button>
                    {editingDepartmentId && (
                      <Button
                        onClick={() => {
                          setEditingDepartmentId(null)
                          departmentForm.resetFields()
                        }}
                      >
                        取消
                      </Button>
                    )}
                  </Space>
                </Form.Item>
              </Form>
            </Card>
          </div>
        </TabPane>

        <TabPane
          tab={
            <span>
              <AppstoreOutlined /> 主机类型
            </span>
          }
          key="hostTypes"
        >
          <div style={{ display: "flex", gap: "24px" }}>
            <Card className="enhanced-card" style={{ flex: 1 }}>
              <Title level={5} style={{ marginBottom: "16px" }}>
                主机类型列表
              </Title>
              <Table
                columns={hostTypeColumns}
                dataSource={hostTypes}
                rowKey="id"
                pagination={{ pageSize: 10 }}
                className="enhanced-table"
              />
            </Card>

            <Card className="enhanced-card" style={{ width: "350px" }}>
              <Title level={5} style={{ marginBottom: "16px" }}>
                {editingHostTypeId ? "编辑主机类型" : "添加主机类型"}
              </Title>
              <Form form={hostTypeForm} layout="vertical" onFinish={handleAddHostType}>
                <Form.Item name="name" label="类型名称" rules={[{ required: true, message: "请输入类型名称" }]}>
                  <Input placeholder="如：前端" />
                </Form.Item>
                <Form.Item name="code" label="类型代码" rules={[{ required: true, message: "请输入类型代码" }]}>
                  <Input placeholder="如：frontend" />
                </Form.Item>
                <Form.Item name="color" label="类型颜色">
                  <ColorPicker
                    showText
                    format="hex"
                    value={hostTypeForm.getFieldValue("color") || "#3b82f6"}
                    onChange={(color, hex) => hostTypeForm.setFieldValue("color", hex)}
                  />
                </Form.Item>
                <Form.Item name="icon" label="类型图标">
                  <Select placeholder="请选择图标">
                    <Select.Option value="GlobalOutlined">
                      <Space>
                        <GlobalOutlined /> 全球图标
                      </Space>
                    </Select.Option>
                    <Select.Option value="ApiOutlined">
                      <Space>
                        <ApiOutlined /> API图标
                      </Space>
                    </Select.Option>
                    <Select.Option value="DatabaseOutlined">
                      <Space>
                        <DatabaseOutlined /> 数据库图标
                      </Space>
                    </Select.Option>
                    <Select.Option value="CloudOutlined">
                      <Space>
                        <CloudOutlined /> 云图标
                      </Space>
                    </Select.Option>
                    <Select.Option value="CodeOutlined">
                      <Space>
                        <CodeOutlined /> 代码图标
                      </Space>
                    </Select.Option>
                    <Select.Option value="AppstoreOutlined">
                      <Space>
                        <AppstoreOutlined /> 应用图标
                      </Space>
                    </Select.Option>
                  </Select>
                </Form.Item>
                <Form.Item name="description" label="类型描述">
                  <TextArea rows={4} placeholder="请输入类型描述" />
                </Form.Item>
                <Form.Item>
                  <Space>
                    <Button
                      type="primary"
                      htmlType="submit"
                      icon={editingHostTypeId ? <EditOutlined /> : <PlusOutlined />}
                    >
                      {editingHostTypeId ? "更新" : "添加"}
                    </Button>
                    {editingHostTypeId && (
                      <Button
                        onClick={() => {
                          setEditingHostTypeId(null)
                          hostTypeForm.resetFields()
                        }}
                      >
                        取消
                      </Button>
                    )}
                  </Space>
                </Form.Item>
              </Form>
            </Card>
          </div>
        </TabPane>
      </Tabs>

      <Modal
        title="无法删除部门"
        open={isDeleteModalVisible}
        onCancel={() => setIsDeleteModalVisible(false)}
        footer={[
          <Button key="ok" type="primary" onClick={() => setIsDeleteModalVisible(false)}>
            我知道了
          </Button>,
        ]}
      >
        <p>
          无法删除部门 "{departmentToDelete?.name}"，因为该部门下还有
          {projects.filter((p) => p.departmentId === departmentToDelete?.id).length} 个项目。
        </p>
        <p>请先删除该部门下的所有项目，然后再尝试删除部门。</p>
      </Modal>
    </div>
  )
}

export default SettingsPage
